package com.heima.search.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/28
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ApUserSearchService apUserSearchService;
    /**
     * ES文章分页搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //校验参数
        if (ObjectUtil.isEmpty(dto) || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtil.getApUser();

        //异步调用 保存搜索记录
        if(ObjectUtil.isNotEmpty(apUser) && dto.getFromIndex() == 0){
            apUserSearchService.insert(dto.getSearchWords(), apUser.getId());
        }
        //设置查询条件
        SearchRequest searchRequest = new SearchRequest(ArticleConstants.SEARCH_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //关键字的分词之后查询
        boolQueryBuilder.must(QueryBuilders
                .queryStringQuery(dto.getSearchWords())
                .field(ArticleConstants.SEARCH_FIELD_TITLE)
                .field(ArticleConstants.SEARCH_FIELD_CONTENT)
                .defaultOperator(Operator.OR)
        );
        //查询小于mindate的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders
                .rangeQuery(ArticleConstants.SEARCH_RANGE_PUBLISHTIME)
                .lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);
        //分页查询
        searchSourceBuilder.from(0).size(dto.getPageSize());
        //按照发布时间倒序查询
        searchSourceBuilder.sort(ArticleConstants.SEARCH_RANGE_PUBLISHTIME, SortOrder.DESC);
        //设置高亮 tittle
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field(ArticleConstants.SEARCH_FIELD_TITLE);
        highlightBuilder.preTags(ArticleConstants.SEARCH_HIGHLIGHT_HEADER);
        highlightBuilder.postTags(ArticleConstants.SEARCH_HIGHLIGHT_END);
        searchSourceBuilder.highlighter(highlightBuilder);
        //查询
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = null;
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //结果封装返回
        return responseHandler(response);
    }

    /**
     * 处理搜索响应结果
     * @param response
     * @return
     */
    private ResponseResult responseHandler(SearchResponse response) {
        List<Map> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
                Text[] titles = hit.getHighlightFields()
                        .get(ArticleConstants.SEARCH_FIELD_TITLE)
                        .getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put(ArticleConstants.SEARCH_RESPONSE_HIGHLIGHT,title);
            }else {
                //原始标题
                map.put(ArticleConstants.SEARCH_RESPONSE_HIGHLIGHT,
                        map.get(ArticleConstants.SEARCH_FIELD_TITLE));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}
